package de.baumann.browser.activitys.oc

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.Toast
import de.baumann.browser.R
import de.baumann.browser.base.BaseOdinActivity
import de.baumann.browser.db.ETHWallet
import de.baumann.browser.iview.IWalletBalanceView
import de.baumann.browser.present.WalletBalancePresenter
import de.baumann.browser.views.dialog.TransferOdinDialog
import de.baumann.browser.views.dialog.PayPwdDialog
import kotlinx.android.synthetic.main.activity_oc_transfer.*
import kotlinx.android.synthetic.main.include_tool_bar.*
import org.web3j.crypto.Credentials
import org.web3j.crypto.WalletUtils
import permissions.dispatcher.RuntimePermissions
import java.io.File

@RuntimePermissions
class OcTransferActivity : BaseOdinActivity<IWalletBalanceView, WalletBalancePresenter>(), IWalletBalanceView {

    companion object {
        const val SCAN = 4000;
        fun startOcTransferActivity(context: Context, ethWallet: ETHWallet) {
            context.startActivity(Intent(context, OcTransferActivity::class.java).apply {

                val bundel = Bundle().apply {
                    putSerializable("odinWallet", ethWallet)
                }
                putExtras(bundel)
            })
        }
    }

    override fun getLayout(): Int {
        return R.layout.activity_oc_transfer
    }

    override fun getTitleText(): String {
        return "转账"
    }

    override fun initView() {
        initToolbar(commToolBar, commTitle)
        btnOcTransfer.setOnClickListener {
            if (checkInput()) {
                TransferOdinDialog(mContext, object : TransferOdinDialog.Callback {
                    override fun callback() {
                        showPwdDialog()
                    }
                }).show()
            }
        }

        tvAllOdin.setOnClickListener {
            edOdinAmount.setText(balance)
        }
    }

    private var password = ""
    private var pwdd: PayPwdDialog? = null
    private fun showPwdDialog() {
        pwdd = PayPwdDialog(mContext, object : PayPwdDialog.PwdCallback {
            override fun callback(pwd: String) {
                password = pwd
                if (getFromAddress().isEmpty()) {
                    return
                }

                if (getPrivateKey().isEmpty()) {
                    return
                }
                showLoading()
                presenter.transfer()
                pwdd!!.dismiss()
            }
        })
        pwdd!!.show()
    }

    override fun onResume() {
        super.onResume()

    }
    private fun checkInput(): Boolean {
        if (getToAddress().isEmpty()) {
            showShortToast("请输入收款地址")
            return false
        }

        if (!WalletUtils.isValidAddress(getToAddress())) {
            showShortToast("收款地址格式错误")
            return false
        }

        if (getAmount().isEmpty()) {
            showShortToast("请输入数量")
            return false
        }
        return true
    }

    override fun initData() {
        presenter.getWalletBalance()
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.menu_sacn, menu)
        return super.onCreateOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        ScanActivity.startScanActivity(this, SCAN)
        return super.onOptionsItemSelected(item)
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != Activity.RESULT_OK) {
            return
        }

        if (requestCode != SCAN) {
            return
        }

        if (data == null) {
            return
        }

        val toAddress = data.getStringExtra("toAddress")
        edToAddress.setText(toAddress)

    }


    override fun getToAddress(): String {
        var address = edToAddress.text.toString().trim()
        if (address.isEmpty()) {
            return ""
        }

        if (address.startsWith("odx")) {
            address = "0${address.substring(2)}"
        }

        return address
    }

    override fun getAmount(): String {
        return edOdinAmount.text.toString().trim()
    }

    override fun getFee(): String {
        return edFee.text.toString().trim()
    }

    override fun getLimit(): Long {
        return 0
    }

    override fun createPresenter(): WalletBalancePresenter {
        return WalletBalancePresenter()
    }

    override fun createView(): IWalletBalanceView {
        return this
    }

    override fun getAddress(): String {
        return getWallet().getAddress()
    }

    private var balance = ""
    override fun setBalance(balance: String) {
        this.balance = balance
        tvBalance.text = "可用 $balance ODIN"
    }

    override fun getFromAddress(): String {
        if (getCredentials() == null) {
            return ""
        }
        return getCredentials()!!.address
    }

    override fun getPrivateKey(): String {
        if (getCredentials() == null) {
            return ""
        }
        return getCredentials()!!.ecKeyPair.privateKey.toString(16)
    }

    private fun getWallet(): ETHWallet {
        return intent.getSerializableExtra("odinWallet") as ETHWallet
    }

    private fun getCredentials(): Credentials? {
        try {
            return WalletUtils.loadCredentials(password, File(getWallet().keystorePath))
        } catch (e: Exception) {
            if ("Invalid password provided" == e.message) {
                Toast.makeText(mContext, "密码错误", Toast.LENGTH_SHORT).show()
            } else {
                Toast.makeText(mContext, e.message, Toast.LENGTH_SHORT).show()
            }
        }
        return null
    }

    override fun transferSuccess(hash: String) {
        hideLoading()
        showShortToast("转账已提交，请等待处理")
        finish()
    }

    override fun showBindEth(): Boolean {
        return false
    }
}
